package com.letianpai.db;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DBUtiles {
    // 保存聊天记录
    public static void saveChatInformation(ChatInformation chat,
                                           Context context, String DBName) {
        Myhelper helper = new Myhelper(context, "chat.db", DBName, null, 1);
        SQLiteDatabase db = helper.getWritableDatabase();
        String sql = "create table if not exists "
                + "db_"
                + DBName
                + " (_id integer primary key autoincrement,uname varchar(100),information varchar(1000))";
        db.execSQL(sql);
        ContentValues values = new ContentValues();
        values.put("uname", chat.getuId());
        values.put("information", chat.getChatInformation());
        db.insert("db_" + DBName, null, values);

    }

    // 查询聊天记录
    public static ArrayList<String> selectInformation(Context context,
                                                      String DBName, String chatName) {
        ArrayList<String> list = new ArrayList<String>();
        Myhelper helper = new Myhelper(context, "chat.db", DBName, null, 1);
        SQLiteDatabase db = helper.getWritableDatabase();
        String sql = "create table if not exists "
                + "db_"
                + DBName
                + " ( _id integer primary key autoincrement , uname varchar(100), information varchar(1000))";
        db.execSQL(sql);
        Cursor cursor = db.query("db_" + DBName,
                new String[] { "information" }, "uname=?",
                new String[] { chatName }, null, null, null);
        while (cursor.moveToNext()) {
            String a = cursor.getString(0); // 获取第一列的值,第一列的索引从0开始
            list.add(a);
        }
        cursor.close();
        db.close();
        return list;
    }
    // 删除聊天记录
    public static void deleteDB(Context context,String DBName){
        Myhelper helper = new Myhelper(context, "chat.db", DBName, null, 1);
        SQLiteDatabase db = helper.getWritableDatabase();
        String sql = "create table if not exists "
                + "db_"
                + DBName
                + " ( _id integer primary key autoincrement , uname varchar(100), information varchar(1000))";
        db.execSQL(sql);
        db.execSQL("drop table if exists "+ "db_"+DBName);
        db.close();
    }
}
